package org.example.steamshop.repository;

import org.example.steamshop.model.CartItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

public interface CartItemRepository extends JpaRepository<CartItem, Long> {

    // 根据用户ID查询购物车列表
    List<CartItem> findByUserId(Long userId);

    // 根据用户ID和游戏ID查询购物车项
    Optional<CartItem> findByUserIdAndGameId(Long userId, Long gameId);

    // 根据用户ID和游戏ID删除购物车项
    void deleteByUserIdAndGameId(Long userId, Long gameId);

    @Modifying
    @Transactional
    @Query("UPDATE CartItem ci SET ci.quantity = :quantity WHERE ci.user.id = :userId AND ci.game.id = :gameId")
    void updateCartItemQuantity(@Param("userId") Long userId,
                                @Param("gameId") Long gameId,
                                @Param("quantity") int quantity);

    void deleteByUserId(Long userId);


}